import { defineStore } from 'pinia';

const dataStore = defineStore('router', {
  state: () => ({
    //预设缓存组件
    cacheRouteName: [],
    //缓存组件
    routeName: [],
    //缓存界面配置
    routeList: [],
    //需要刷新的界面
    refreshName: '',
    //上一个路由
    previousRoute: null,
    //是否需要刷新列表
    needRefreshList: false
  }),
  actions: {
    //添加缓存组件
    addCacheRoute(value) {
      if (!this.cacheRouteName.includes(value)) {
        this.cacheRouteName.push(value);
      }
    },
    removeCacheRoute(value) {
      const index = this.cacheRouteName.indexOf(value);
      if (index > -1) {
        this.cacheRouteName.splice(index, 1);
      }
    },
    addRouteName(value) {
      if (!this.routeName.includes(value.name)) {
        this.routeName.push(value.name);
        this.routeList.push(value);
      }
    },
    removeRouteName(value) {
      const index = this.routeName.indexOf(value);
      if (index > -1) {
        this.routeName.splice(index, 1);
        this.routeList = this.routeList.filter((route) => route.name !== value);
      }
    },
    //刷新
    addRefreshName(value) {
      this.refreshName = value;
    }, // 添加逗号

    // 处理路由前进
    handleForward(route) {
      if (!this.routeName.includes(route.name)) {
        this.routeName.push(route.name);
        this.routeList.push(route);
      }
      this.previousRoute = route;
    },

    // 处理路由后退
    handleBack(route) {
      if (this.previousRoute && this.needRefreshList) {
        this.addRefreshName(route.name);
        this.needRefreshList = false;
      }

      const index = this.routeName.indexOf(route.name);
      if (index > -1) {
        this.routeName.splice(index);
        this.routeList = this.routeList.filter((_, idx) => idx <= index);
      }
      this.previousRoute = route;
    },

    // 标记需要刷新列表
    markListNeedRefresh() {
      this.needRefreshList = true;
    }
  },
  getters: {
    shouldRefresh: (state) => (routeName) => {
      return state.refreshName === routeName;
    }
  }
});

export default dataStore;
